
const express = require("express");
const { resSuc, resErr } = require('../utils/resMsg.js');
const bodyParser = require("body-parser");
const itemService = require("../../node/service/itemService.js");

const router = express.Router();

router.get("/", (req, res) => {
    itemService.getAll().then(rows => {
        res.json(resSuc(rows));
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
})

router.post("*", bodyParser.urlencoded({ extended: true }));
router.post("*", bodyParser.json());

// Add Item
router.post("/add", (req, res) => {
    itemService.add(req.body).then(lastID => {
        res.json(resSuc(lastID))
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
})

// Delete Item
router.post("/delete", (req, res) => {
    console.log(req.body)
    itemService.delete(req.body.id).then(() => { 
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
})

// Update Item
router.post("/update", (req, res) => {
    itemService.update(req.body).then(() => { 
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
})

// Update Items
router.post("/updateall", (req, res) => {
    itemService.updateAll(req.body).then(() => { 
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
})

// 保存数据到本地js文件
router.post("/save", (req, res) => {
    itemService.saveAllItems().then(() => {
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
})


module.exports = router;

